package com.jiuyun.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiuyun.entity.JsonResult;
import com.jiuyun.entity.Users;
import com.jiuyun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Spring + SpringMvc + Mybatis = SSM
 * CrossOrigin 支持跨域
 */
@Controller
@CrossOrigin
public class UsersController {

    @Autowired
    UserService userService;

    @GetMapping("/users")
    public String index(ModelMap map, @RequestParam(value = "page", defaultValue = "1") int page) {
        System.out.println("进入 UsersController 控制器 1...");
        PageHelper.startPage(page, 5);
        List<Object> list = userService.getAll();

        PageInfo<?> pInfo = new PageInfo<>(list);
        map.put("pInfo", pInfo);
        return "index"; // index.jsp
    }

    @GetMapping("index")
    public String toIndex() {
        return "index";
    }

    @GetMapping("/ajaxUsers")
    @ResponseBody // 把返回对象变成 JSON 对象
    public JsonResult ajax(ModelMap map, @RequestParam(value = "page", defaultValue = "1") int page) {
        System.out.println("进入 UsersController 控制器 2...");
        PageHelper.startPage(page, 5);
        List<Object> list = userService.getAll();
        PageInfo<?> pInfo = new PageInfo<>(list);
        return (!list.isEmpty()) ? new JsonResult(200, "获取列表成功！！！", pInfo)
                : new JsonResult(404, "获取列表失败！！！", null); // index.jsp
    }

    @PostMapping("/users")
    @ResponseBody
    public JsonResult add(Users user) {
        int row = userService.add(user);
        return row > 0 ? new JsonResult(200, "添加用户信息成功！！！", null)
                : new JsonResult(404, "添加用户信息失败！！！", null);
    }

    @PutMapping("/users")
    @ResponseBody
    public JsonResult update(@RequestBody Users user) {
        int row = userService.update(user);
        return row > 0 ? new JsonResult(200, "更新用户信息成功！！！", null)
                : new JsonResult(404, "更新用户信息失败！！！", null);
    }

    @DeleteMapping("/users/{userId}")
    @ResponseBody
    public JsonResult del(@PathVariable("userId") int userId) {
        int row = userService.del(userId);
        return row > 0 ? new JsonResult(200, "删除用户信息成功！！！", null)
                : new JsonResult(404, "删除用户信息失败！！！", null);
    }

}
